package org.axed.user.client;

import java.util.Stack;

/**
 * Stores unneeded events in a pool. 
 * This should relieve the garbage collector to
 * have to constantly collect things that otherwise
 * would in mass be created and become unreferenced
 * short after.
 */
public class AxedEventPool {
	Stack[] pools = new Stack[AxedEvent.MAX_ID];
	AxedArea axed;

	/**
	 * Constructor
	 */
	AxedEventPool(AxedArea axed) {
		this.axed = axed;
		for (int i = 0; i < AxedEvent.MAX_ID; i++) {
			pools[i] = new Stack();
		}
	}

	/**
	 * Pulls an event from the pool if available or
	 * creates a new one if pool empty.
	 */
	public AxedEvent newEvent(int atomicID, int type) {
		int id = AxedEvent.getClassId(type);
		AxedEvent e;
		if (pools[id].size() > 0) {
			e = (AxedEvent) pools[id].pop();
		} else {
			e = new AxedEvent();
			e.create(id, axed);
		}
		e.atomicID = atomicID;
		return e;
	}

	/**
	 * Puts an event into the Pool to be not
	 * used again, until its pulled by newEvent(),
	 */
	public void releaseEvent(AxedEvent e) {
		pools[AxedEvent.getClassId(e.type)].push(e);
	}
}
